package com.cfuture08.eweb4j.mvc.action;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cfuture08.eweb4j.component.json.JsonConverter;
import com.cfuture08.eweb4j.mvc.config.MVCConfigConstant;

/**
 * MVC组件Action抽象类，实现初始化方法，将request和response两个对象从过滤器中传进来
 * 
 * @author cfuture.aw
 * @since v1.a.0
 */
public abstract class ActionSupport implements Action {
	public HttpServletRequest request;
	public HttpServletResponse response;
	public PrintWriter out;

	public void init(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.request = request;
		this.response = response;
		this.out = response.getWriter();
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public <T> String Json(T t) {
		this.out.print(JsonConverter.convert(t));
		return JSON_OUT;
	}
	
	public <T> String Json(String key, T t) {
		this.out.print(JsonConverter.convert(key, t));
		return JSON_OUT;
	}
	
	public <T> String Json(String[] key, T[] t) {
		this.out.print(JsonConverter.convert(key, t));
		return JSON_OUT;
	}
	
	public <T> String Json(T... t) {
		this.out.print(JsonConverter.convertWithDefaultKey(t));
		return JSON_OUT;
	}

	public <T> String setJson(T... t) {
		this.request.setAttribute(MVCConfigConstant.JSON_ATTR, JsonConverter
				.convert(t));
		return JSON;
	}

	public String Ajax(String message) {
		this.out.print(message);
		return AJAX_OUT;
	}

	public String setAjax(String message) {
		this.request.setAttribute(MVCConfigConstant.AJAX_ATTR, message);
		return AJAX;
	}
}
